/*
 * create:2016年4月15日 下午1:48:03
 * author:wangds  
 */
package com.cxkj.shop.proc;

import java.util.Collection;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.cxkj.shop.model.order.Order;
import com.cxkj.shop.model.order.OrderItem;

import net.wangds.utilities.lang.CloseableUtils;
import net.wangds.utilities.lang.StringUtils;

/**
 * .
 * 
 * @author wangds
 *
 */
public class InsOrderProc extends AbstractWithResMybatisProc<Order, Integer> {

  private String sqlId4Item;

  /**
   * The getter method of the property sqlId4Item.
   * 
   * @author wangds 2016年4月15日 下午1:50:53.
   * @return the sqlId4Item.
   */
  public String getSqlId4Item() {
    return sqlId4Item;
  }

  /**
   * The setter method of the property sqlId4Item.
   * 
   * @param thesqlId4Item
   *          the sqlId4Item to set
   * @author wangds 2016年4月15日 下午1:50:53.
   */
  public void setSqlId4Item(String sqlId4Item) {
    this.sqlId4Item = sqlId4Item;
  }

  /*
   * @see net.wangds.common.processor.AbstractProcessorWithResult#execute()
   * 
   * @author wangds 2016年4月15日 下午1:48:51.
   */
  @Override
  protected Integer execute() {
    int res = 0;

    Order order = this.getParameter();
    Collection<OrderItem> items = order.getItems();

    SqlSessionFactory fac = this.getSessionFac();
    SqlSession ssn = null;
    try {
      ssn = fac.openSession(false);
      int op_res = 0;
      op_res = ssn.insert("insOrder", order);
      if (op_res >= 0) {
        res += op_res;
      } else {
        res = op_res;
        throw new Exception();
      }
      for (OrderItem item : items) {
        
        String old = item.getCommodityId();
        int gid = item.getGrouppayId();
        int tid = item.getTimelimitpayId();
        @SuppressWarnings("unchecked")
        String nid = StringUtils.join(old,"_",(gid>0?gid:""),"_",(tid>0?tid:""));
        item.setCommodityId(nid);
        op_res = ssn.insert("insOrderItem", item);
        item.setCommodityId(old);
        if (op_res >= 0) {
          res += op_res;
        } else {
          res = op_res;
          break;
        }
      }
      
      if(op_res<0){
        throw new Exception();
      }

      ssn.commit();

    } catch (Exception e) {
      ssn.rollback();
      throw new RuntimeException(e);
    } finally {
      CloseableUtils.close(ssn);
    }

    return res;
  }

}
